package routeFunctions;

import java.util.ArrayList;
import XMLread.*;

public class RouteInfo {
	private Route ourRoute;

	public RouteInfo(Object start, Object end, Building building){
		setOurRoute(getRoute(start, end, building, new Route()));
	}

	public Route getOurRoute() {
		return ourRoute;
	}

	public void setOurRoute(Route ourRoute) {
		this.ourRoute = ourRoute;
	}

	private Route getRoute(Object start, Object end, Building building, Route route){
		//we are at our ending location so return our route
		if(start.equals(end)){
			return route;
		}
		//we have already passed the start location we went in loop not most efficient path return null
		else if(route.hasBeenTraversed(start)){
			return null;
		}
		//add our start location to list of traversed entities so we don't traverse it again
		route.addTraversed(start);

		//find out where we are in the building
		ArrayList<Object> entities = new ArrayList<Object>();
		int startIndex = 0;
		for(Floor f : building.getFloors()){
			for(Hallway h : f.getHallways()){
				if(h.getEntities().contains(start)){
					entities = h.getEntities();
					startIndex = entities.indexOf(start);
				}
			}
		}

		//our start location is a Space
		if(start instanceof Space){

			//we are at the start of the hallway
			if(startIndex == 0)
				return getRoute(entities.get(1), end, building, route);


			//we are the end of a hallway
			else if(startIndex == entities.size()-1)
				return getRoute(entities.get(startIndex-2), end, building, route);


			//we are in the middle of a hallway
			else{

				Route tempRoute = getRoute(entities.get(startIndex+1), end, building, route);
				if(tempRoute == null){ //we already went this direction so go the other way
					return getRoute(entities.get(startIndex-1), end, building, route);
				}
				Route tempRoute2 = getRoute(entities.get(startIndex-1), end, building, route);
				if(tempRoute2 != null && tempRoute.getTraversedSize()< tempRoute2.getTraversedSize()){
					return tempRoute;
				}
				return tempRoute2;
			}
		}

		//start location is an Intersection
		else if(start instanceof Intersection){
			return null;
		}
		//start in an instance of Exit
		else if(start instanceof Exit){
			return null;
		}
		//start location is a Stairwell
		return null;


	}
}
